<template>
  <div class="form-content">
    <el-form
      ref="formRef"
      label-position="top"
      :model="form"
      :rules="formRules"
      class="form-content"
    >
      <el-form-item label="SMTP 服务器" prop="smtpHost">
        <el-input type="text" v-model="form.smtpHost"  placeholder="请输入SMTP 服务器" />
      </el-form-item>
      <el-form-item label="SMTP 端口" prop="smtpPort">
        <el-input type="text" v-model="form.smtpPort"  placeholder="请输入SMTP 端口" />
      </el-form-item>
      <el-form-item label="SMTP 用户名" prop="smtpUsername">
        <el-input type="text" v-model="form.smtpUsername"  placeholder="请输入SMTP 用户名" />
      </el-form-item>
      <el-form-item label="SMTP 密码" prop="smtpPassword">
        <el-input type="password" show-password v-model="form.smtpPassword"  placeholder="请输入SMTP 密码" />
      </el-form-item>
      <el-form-item label="SMTP 发件人邮箱" prop="smtpSendEmail">
        <el-input type="text" v-model="form.smtpSendEmail"  placeholder="请输入SMTP 发件人邮箱" />
      </el-form-item>
    </el-form>
    <footer>
      <el-button v-if="false" type="default" plain>邮件测试发送</el-button>
      <el-button
        v-permission="'system-config-permission:btn:edit'"
        type="primary"
        @click="submitConfigInfo">立即保存</el-button>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ruleRequired, ruleMaxLength, RULE_PORT, RULE_EMAIL } from '@/utils/rules'
import { ElMessage } from 'element-plus'
import { apiSetConfig } from '@/http/service'

const props = defineProps({
  configForm: {
    type: Object,
    default: () => null
  }
})
const form = reactive({
  smtpHost: '',
  smtpPort: null,
  smtpUsername: '',
  smtpPassword: '',
  smtpSendEmail: ''
})
const formRules = reactive<FormRules>({
  smtpHost: [ruleRequired('请输入SMTP 服务器'), ruleMaxLength(32)],
  smtpPort: [ruleRequired('请输入SMTP 端口号'), RULE_PORT],
  smtpUsername: [ruleRequired('请输入SMTP 用户名'), ruleMaxLength(32)],
  smtpPassword: [ruleRequired('请输入SMTP 密码'), ruleMaxLength(32)],
  smtpSendEmail: [ruleRequired('请输入SMTP 发件人邮箱'), RULE_EMAIL]
})
const formRef = ref<null | FormInstance>(null)

watch(() => props.configForm, val => {
  if (val) {
    const { smtpHost, smtpPort, smtpUsername, smtpPassword, smtpSendEmail } = val
    Object.assign(form, {
      smtpHost, smtpPort, smtpUsername, smtpPassword, smtpSendEmail
    })
  }
})

async function submitConfigInfo () {
  const valid = await formRef.value?.validate()
  if (valid) {
    await apiSetConfig(form)
    ElMessage.success('更新邮件配置信息成功')
  }
}
</script>

<style lang="scss" scoped>
.form-content {
  padding: 10px 20px 0;
  width: 800px;
  height: 100%;
  display: flex;
  flex-direction: column;
  .el-form {
    flex: 1;
  }
  footer {
    padding-left: 20px;
  }
}
</style>
